﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using WeBlog.Interfaces;
using WeBlog.Repositories;
using WeBlog.Services;

namespace WeBlog.Models
{
    public class PostDetailsViewModel
    {
        private readonly PostRepository _repository;
        public Post Post { get; private set; }
        public PostComment Comment { get; private set; }
        public IEnumerable<PostComment> ApprovedComments { get; private set; }
        private readonly IUnitOfWork _unitOfWork;
        private SiteConfiguration _siteConfiguration;

        private PostDetailsViewModel( IUnitOfWork unitOfWork )
        {
            _unitOfWork = unitOfWork;
            _repository = new PostRepository(unitOfWork);
        }

        public PostDetailsViewModel(IUnitOfWork unitOfWork, int id)
            : this(unitOfWork)
        {
            Post = _repository.Find(id);
            Hydrate();
        }

        public PostDetailsViewModel(IUnitOfWork unitOfWork, string slug)
            : this(unitOfWork)
        {
            Post = _repository.FindBySlug(slug);
            Hydrate();
        }

        private void Hydrate()
        {
            if (Post == null) throw new NotFoundException();
            _siteConfiguration = SiteManager.CurrentConfiguration;

            Comment = new PostComment {
                DateTime = DateTime.Now
            };
            ApprovedComments = Post.ApprovedComments;
        }

        public void Update( User user, HttpRequestBase request  )
        {
            if (user.IsInRole(Role.Admin) || user.IsInRole(Role.Editor))
                Comment.CommentStatus = CommentStatuses.Approved;
            else
                Comment.CommentStatus = _siteConfiguration.ModerateComments ? CommentStatuses.Pending : CommentStatuses.Approved;

            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
                Comment.UserId = user.UserId;

            if( request != null )
                Comment.IpAddress = request.UserHostAddress;
        }

        public void SaveComment()
        {
            Post.PostComments.Add( Comment );
            _unitOfWork.Commit();
        }
    }
}